import type { RobotTagResult } from "@/api/zyApi.ts";
import { pinyin } from "pinyin-pro";

/**
 * 自定扩展类型基类
 * 便于扩展自定义属性label和children
 * 由于children中的类型参数不同，取消使用泛型
 */
export interface CurtBase extends RobotTagResult, RobotTagResult {
    label: string;
    children: any[];
    [key: string]: any;
}

/**
 * 构建树形列表
 * @param list
 */
export const buildTree = (list: CurtBase[]) => {
    const treeList: CurtBase[] = [];
    const otherTree: Partial<CurtBase> = {
        label: "其他",
        children: [] as any[],
        chart: "Z"
    };
    if (!list || list.length === 0) return [];
    // 构建分类标签以及对机器人分类
    list.forEach((item: CurtBase) => {
        const tags: CurtBase[] = item.Tags || [];
        item.label = item.Nick;
        if (tags.length === 0) {
            otherTree.children!.push(item);
            return;
        }
        // 提取分类并将当前机器人放入对应的分类中
        tags.forEach(tag => {
            const findTree = treeList.find(tree => tree.Name === tag.Name);
            tag.children = [];
            tag.label = tag.Name;
            tag.chart = pinyin(tag.Name.slice(0, 1), { toneType: 'none' }).charAt(0).toUpperCase();
            if (!findTree) {
                tag.children.push(item);
                treeList.push(tag);
            } else {
                findTree.children.push(item);
            }
        })
    })
    // 其他类型也是Z序列的放最后
    treeList.push(otherTree as CurtBase);
    const result: Partial<CurtBase>[] = [];
    // 构建字母
    treeList.forEach(item => {
        const res = result.find(re => re.chart === item.chart);
        if (res) {
            res.children!.push(item);
        } else {
            result.push({ label: item.chart, children: [item] })
        }
    });
    return result;
};
